package hutech.ksv.dao;

import hutech.ksv.entity.ThongTinUngVienEntity;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class TTUngVienDao implements Serializable {

	@Autowired
	DataSource dataSource;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Test connection
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/mydb", "root", "mysql@123");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// Load thong tin
	public List<ThongTinUngVienEntity> loadThongTinUV() {
		String query = "SELECT * FROM `ThongTinUngVien`";
		List<ThongTinUngVienEntity> listThongTinUV = new ArrayList<ThongTinUngVienEntity>();

		Connection conn = null;
		PreparedStatement preparedStatement = null;

		try {
			conn = dataSource.getConnection();
			preparedStatement = conn.prepareStatement(query);
			ResultSet rs = preparedStatement.executeQuery();
			while (rs.next()) {
				listThongTinUV.add(new ThongTinUngVienEntity(rs.getString(1), rs.getInt(2), 
									rs.getInt(3), rs.getDate(4)));
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return listThongTinUV;
	}
}
